package gov.jslt.app.update;

import gov.jslt.app.config.BootStrat;
import gov.jslt.app.tool.FileMD5;
import gov.jslt.app.tool.XmlTool;
import gov.jslt.app.vo.VesionV0;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.sax.Element;


public class UpdateInfoService {
	ProgressDialog progressDialog;
	Handler handler;
	Context context;
	VesionV0 updateInfo;
	
	public UpdateInfoService(Context context){
		this.context=context;
	}
	
	public VesionV0 getUpDateInfo() throws Exception{
		String url=(String)BootStrat.singleton(context.getApplicationContext()).getValue("app.update.url");
		updateInfo = XmlTool.GetRemoteVesionInfo(url);
		this.updateInfo =updateInfo;
		return updateInfo;
		
	}

	public boolean isNeedUpdate() {
		// TODO Auto-generated method stub
		String new_version = updateInfo.getBbh();//最新版本的版本号
		//获取当前版本号
		String now_version = "";
		try{
			PackageManager packageManager = context.getPackageManager();
			PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
			now_version = packageInfo.versionName;
		}catch(NameNotFoundException e){
			e.printStackTrace();
		}
		if(new_version.equals(now_version)){
			return false;
		}else{
			return true;
		}
	}
	
	public void downLoadFile(final String url,final ProgressDialog pDialog,Handler h){
		progressDialog = pDialog;
		handler = h;
		new Thread(){
			public void run(){
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try{
					response = client.execute(get);
					HttpEntity entity= response.getEntity();
					//获取文件大小
					int length = (int) entity.getContentLength();
					//设置进度条的总长度
					progressDialog.setMax(length/1024);
					progressDialog.setProgressNumberFormat("%1d kb/%2d kb");
					InputStream is =entity.getContent();
					
					FileOutputStream fileOutputStream = null;
					if(is !=null){
						File file=new File(
								Environment.getExternalStorageDirectory(),"zsbs.apk");
						fileOutputStream = new FileOutputStream(file);
						//数据缓冲区
						byte[] buf =new byte[1024*1024];
						int ch =-1;
						int process = 0;
						while((ch = is.read(buf))!= -1){
							fileOutputStream .write(buf,0,ch);
							process+=ch;
							//这里就是关键的实时更新进度了！
							progressDialog.setProgress(process/1024);
						}
					}
					fileOutputStream.flush();
					if(fileOutputStream !=null){
						fileOutputStream.close();
					}
					String checkMd5 = updateInfo.getCheckMd5();
					//下载完apk，生成MD5
					String md5= FileMD5.getFileMD5(new File(Environment.getExternalStorageDirectory(),"zsbs.apk"));
					if(!checkMd5.equals(md5)){
						progressDialog.cancel();
						Message message = new Message();
						message.what = 2; 
						handler.sendMessage(message);
						
					}else{
						down();
					}
				}catch(ClientProtocolException e){
					e.printStackTrace();
				}catch(IOException e){
					e.printStackTrace();
				}
				
			}
		}.start();
	}
	
	void down(){
		handler.post(new Runnable(){
			public void run(){
				progressDialog.cancel();
				update();
			}
		});
	}
	
	void update(){
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(),"zsbs.apk")), 
				"application/vnd.android.package-archive");
		context.startActivity(intent);
	}
	
}
